package cse.om.spellchecker;

import java.io.IOException;
import java.util.HashMap;
import java.util.HashSet;
import java.util.Map;
import java.util.Set;

import cse.om.common.UTF8File;

public class Dictionary {

	private final static String DICTIONARY_PATH = "resources/om/dictionary.txt";
//	private final static String DICTIONARY_PATH = "resources/dictionary_full.txt";
	private final static String CHARSET_PATH = "resources/om/vietcharset.txt";
	private static Map<String, String> dict;
	private static Set<Character> charSet;
	private static Set<Character> vowels, consonants;

	static {
		try {
			readDictionaryFromFile(DICTIONARY_PATH);
			readCharSetFromFile(CHARSET_PATH);
		} catch (IOException e) {
			System.out.println(e.getMessage());
		}
	}

	private static void readDictionaryFromFile(String filePath)
		throws IOException {
		String[] lines = UTF8File.getAllLines(filePath);
		dict = new HashMap<>();
		for (String line : lines) {
			String[] data = line.split("\t");
			if (data.length >= 2) {
				dict.put(data[0], data[1]);
			}
		}
	}

	public static String getDefination(String word) {
		if (dict.containsKey(word)) {
			return dict.get(word);
		} else if (dict.containsKey(word.toLowerCase())) {
			char[] res = dict.get(word.toLowerCase()).toCharArray();
			if (word.length() > 1 && word.toUpperCase().compareTo(word) == 0) {
				for (int i = 0; i < res.length; ++i)
					res[i] = Character.toUpperCase(res[i]);
			} else
				res[0] = Character.toUpperCase(res[0]);
			return String.valueOf(res);
		} else {
			return word;
		}
	}

	private static void readCharSetFromFile(String filePath) throws IOException {
		String[] lines = UTF8File.getAllLines(filePath);
		charSet = new HashSet<>();
		vowels = new HashSet<>();
		consonants = new HashSet<>();
		for (int i = 0; i < lines.length; ++i) {
			String line = lines[i];
			for (char c : line.toCharArray()) {
				if (c != ' ' && c != '\t') {
					charSet.add(Character.toLowerCase(c));
					charSet.add(Character.toUpperCase(c));
					if (i == 0) {
						vowels.add(Character.toLowerCase(c));
						vowels.add(Character.toUpperCase(c));
					} else if (i == 1) {
						consonants.add(Character.toLowerCase(c));
						consonants.add(Character.toUpperCase(c));
					}
				}
			}
		}
	}

	public static boolean isVietnameseCharacter(char c) {
		return charSet.contains(c);
	}

	public static boolean isVowel(char c) {
		return vowels.contains(c);
	}

	public static boolean isConsonant(char c) {
		return consonants.contains(c);
	}
}
